#include "pg.h"

int MyDrawLine(int x0, int y0, int x1, int y1, int color)
{
	unsigned char *vptr0;		//pointer to vram
	unsigned char *vptr;		//pointer to vram
	int cx, cy;
	vptr0=(unsigned char*)pgGetVramAddr(x0,y0);
	cx = 0;
	cy = 0;
	if(x0 == x1)
	{
		MyFillRect(x0, y0<y1?y0:y1, 1, y0<y1?(y1-y0):(y0-y1), color);
		return 0;
	}
	if(y0 == y1)
	{
		MyFillRect(x0<x1?x0:x1, y0, x0<x1?(x1-x0):(x0-x1), 1,color);
		return 0;
	}
	if(x1-x0>=y1-y0)
	{
	while(cx != (x1 - x0))
	{
		
		if(cy + y0 < SCREEN_HEIGHT 
			&& cx + x0 < SCREEN_WIDTH
			&& cy + y0 > 0 
			&& cx + x0 > 0)
			*(unsigned short *)(vptr0+ cy * LINESIZE*2 + cx * PIXELSIZE*2) = color;
		cx += (x0 < x1)?1:-1;
		cy = (y1 - y0)*(cx) / (x1- x0);
	}
	}	
	else
	{
	while(cy != (y1 - y0))
	{
		
		if(cy + y0 < SCREEN_HEIGHT 
			&& cx + x0 < SCREEN_WIDTH
			&& cy + y0 > 0 
			&& cx + x0 > 0)
			*(unsigned short *)(vptr0+ cy * LINESIZE*2 + cx * PIXELSIZE*2) = color;
		cy += (y0 < y1)?1:-1;
		cx = (x1 - x0)*(cy) / (y1- y0);
	}
	}
	if(cy + y0 < SCREEN_HEIGHT 
			&& cx + x0 < SCREEN_WIDTH
			&& cy + y0 > 0 
			&& cx + x0 > 0)
			*(unsigned short *)(vptr0+ cy * LINESIZE*2 + cx * PIXELSIZE*2) = color;
	return 0;
}

int MyDrawRect(int x, int y, int width, int height, int color)
{
//	unsigned char *vptr0;		//pointer to vram
	MyDrawLine(x, y , x+width-1, y, color);
	MyDrawLine(x, y , x, y + height-1, color);
	MyDrawLine(x + width-1, y , x+width-1, y + height-1, color);
	MyDrawLine(x , y + height-1, x+width, y + height-1, color);
	
	return 0;
}

int MyFillRect(int x, int y, int width, int height, int color)
{
	unsigned char *vptr0;		//pointer to vram
	unsigned char *vptr;		//pointer to vram
	vptr0=(unsigned char*)pgGetVramAddr(x,y);
	int cy,cx;
	for(cy = 0; cy < height; cy++)
	{
		vptr = vptr0;
		for(cx = 0; cx < width; cx++)
		{
			if(cy + y < SCREEN_HEIGHT 
			&& cx + x < SCREEN_WIDTH
			&& cy + y > 0 
			&& cx + x > 0)
		  *(unsigned short *)vptr=color;
		  vptr+=PIXELSIZE*2;
		}
		vptr0 += LINESIZE*2;
	}
	return 0;
}